﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IProductImageRepository))]
    public partial class EntityRepositories : IProductImageRepository
    {
     
        public IQueryable<IProductImage> ProductImages
        {
            get
            {
                return this.DataReaderContext.ProductImages;
            }
        }

        public void Post(IProductImage productImage)
        {
            Contract.Requires(productImage != null);

            var item = new ProductImage()
            {
                CoverImage = productImage.CoverImage,
                Name = productImage.Name,
                ProductId = productImage.Product.Id
            };

            this.DataWriterContext.ProductImages.InsertOnSubmit(item);
            this.DataWriterContext.SubmitChanges();
        }

        public void Put(IProductImage productImage)
        {
            Contract.Requires(productImage != null);

            var item = this.DataWriterContext.ProductImages
                .Where(i => i.Id == productImage.Id)
                .FirstOrDefault();

            if (item == null)
            {
                throw new KeyNotFoundException("ProductImage: " + productImage.Id);

            }

            item.CoverImage = productImage.CoverImage;
            item.Name = productImage.Name;
            item.ProductId = productImage.Product.Id;

            this.DataWriterContext.SubmitChanges();
        }

        public void Delete(IProductImage productImage)
        {
            if (productImage != null)
            {
                var item = this.DataWriterContext.ProductImages
                .Where(i => i.Id == productImage.Id)
                .FirstOrDefault();

                if (item != null)
                {
                    this.DataWriterContext.ProductImages.DeleteOnSubmit(item);
                    this.DataWriterContext.SubmitChanges();
                }
            }
        }

    }
}
